
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/home/Index.vue'
import NotFound from '../views/notFound/Index.vue'
import Layout from '@/components/layout/Index.vue'
import type { MenuRequestType } from '@/apis/types/menu.d'

import useStore from '@/store'
import { localMenu } from './staticMenu'

interface RouterType {
  path: string,
  redirect: string,
  component: any,
  children?: any,
  [perName: string]: any
}

const routes = [
  {
    path: '/',
    redirect: '/home',
    component: Layout,
    children: [
      {
        path: 'home',
        name: 'home',
        component: Home

      }
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    component: NotFound,
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes: routes
})
function treeToArray(tree: MenuRequestType[]) {
  let arr: MenuRequestType[] = [];
  const expanded = (data: MenuRequestType[]) => {
    if (data && data.length > 0) {
      data.forEach((e: MenuRequestType) => {
        arr.push(e);
        expanded(e.children as MenuRequestType[]);
      });
    }
  };
  expanded(tree);
  return arr;
}
function flattenTree(tree: RouterType[] | any, parentPath = '') {
  let result: RouterType[] = [];
  tree.forEach((node: RouterType) => {
    let path = `${parentPath}/${node.path}`.replace(/\/+/g, '/');
    node.path = path;
    result.push(node);
    if (node.children && node.children.length > 0) {
      result = result.concat(flattenTree(node.children, path));
    }
  });
  return result;
}
router.beforeEach(async (to, from, next) => {
  const { userInfo } = useStore() // 使用 useStore 获取 store 中的数据
  await userInfo.getMenuData()

  if (!userInfo.menuData || userInfo.menuData.length <= 0) {
    next();
    return;
  }

  const dynamicRoutes = userInfo.menuData;
  console.log('dynamicRoutes: ', dynamicRoutes);
  const menuArr = treeToArray(dynamicRoutes)  //菜单树变成数组
  console.log('menuArr: ', menuArr);
  const arr = flattenTree(localMenu)
  console.log('arr: ', arr);

  for (let i = 0; i < menuArr.length; i++) {
    let item = menuArr[i]
    if (item.pagepermisson && item.pagepermisson == 1) {
      const info = arr.find(el => el.path == item.key)
      if (info) {
        router.addRoute(info);
      }
    }
  }

  // dynamicRoutes.forEach(route=>{
  //   router.addRoute(route);
  // })
  console.log('User Info:', userInfo);
  next()
});
export default router
